'use strict';

app.controller('envCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$modal', '$timeout', function ($scope, $http, $stateParams, $rootScope, $filter, $location, $modal, $timeout) {
    $rootScope.clean($scope.app);
    $scope.info = {};
    $scope.info.ApplyInfo = [];
    $scope.info.type = $stateParams.type;
    $scope.info.projectPlanId = $stateParams.id;
    $scope.app.page = {};
    $scope.info.types = [];
    $scope.info.bodyData = "请确认是否删除";
    setStorage('brdBackUrl', $location.url())

    $scope.dataType = [];
    $scope.info.selectReq = null;

    $scope.initTitle = function () {
        if ($scope.info.type == 'add') {
            $scope.info.title = "新增项目计划";
        } else if ($scope.info.type == 'edit') {
            $scope.info.title = "编辑项目计划";
        } else {
            $scope.info.title = "查看项目计划";
        }
    };

    //初始化header数据
    $scope.app.headerPanel.buttons = [];
    var cancel = {
        title: '返回', func: function () {
            $rootScope.backHistory();
        }
    }
    $scope.app.headerPanel.buttons.push(cancel);

    $scope.info.envThdata = [
        {"thName": "环境类型"}, 
        {"thName": "IP"}, 
        {"thName": "ucloud地址"}, 
        {"thName": "状态"}
    ];
    $scope.info.envPage = {"isTrue": true};
    $scope.info.envList = {
        "trIsClick": false,
        "isOperation": {
            "Delete": {"isTrue": true, "msg": "删除申请"}
        },
        "tdName": [{"name": "type"}, {"name": "agent_ip"}, {"name": "ucloudIp", "fun": true}, {"name": "status"}]
    };

    $scope.goToRelease = function (info) {
        if (info.agent_ip != null) {
            window.open(info.ucloudIp);
        }
    }

    //projectPlan详情
    $scope.projectPlanInfo = function () {
        $scope.info.projectPlanInfo = {};
        $.ajax({
            type: "get",
            url: matrix_product_url + '/projectPlan/getProjectPlans?containFinished=Y&projectPlanId=' + $scope.info.projectPlanId,
            async: false,
            success: function (data) {
                if (data.code == 0) {
                    $scope.info.projectPlanInfo = data.data[0];
                } else {
                    $rootScope.showMessage("error", "失败", data.msg);
                }
            }
        });
    }
    $scope.projectPlanInfo();

    $scope.apply_record = function () {
        $http.get(beetle_plan_url + '/project_plan/getUcloudApplyInfo?token_id=' + getTokenId() + '&plan_id=' + $scope.info.projectPlanInfo.uplanId).success(function (data) {
            if (data.success) {
                $scope.info.envList.datas = data.data;
                $scope.info.types = []
                angular.forEach($scope.info.envList.datas, function (data) {
                    $scope.info.types.push(data.type);
                    if (data.agent_ip != null) {
                        data.ucloudIp = beetle_ui_url + "#/menu/newucList/" + data.agent_ip;
                    }
                })
            } else {
                alert(data.msg);
            }
        }).error(function (data) {
            alert(data.message);
        })
    };
    $scope.apply_record();


    //移除申请
    $scope.applyDelete = function (info) {
        $rootScope.confirmWindow($scope.info, function (data) {
            $http.get(ucloud_master_url + '/api/v1/apply_record/removeRecord?token_id=' + getTokenId() + '&plan_id=' + $scope.info.projectPlanInfo.uplanId + '&env_type=' + info.type).success(function (data) {
                if (data.success == true) {
                    $scope.apply_record();
                } else {
                    $rootScope.showMessage("error", "失败", data.msg);
                }
            })
        })
    }
    $scope.addApply = function () {
        var param = {};
        param.plan_id = $scope.info.projectPlanInfo.uplanId;
        param.types = $scope.info.types;
        param.plan_name = $scope.info.projectPlanInfo.projectPlanName;
        param.projectPlanInfo = $scope.info.projectPlanInfo;
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: 'addApply.html',
            controller: 'addApplyCtrl',
            resolve: {
                param: function () {
                    return param;
                }
            }

        });
        modalInstance.result.then(function (result) {
                if (result == 'cancel') {
                    $scope.apply_record();
                }
            },
            function (reason) {
                if (reason == 'cancel') {
                    $scope.apply_record();
                }
            });
    }

}]);
app.controller('addApplyCtrl', ['$scope', '$rootScope', '$modalInstance', 'param', '$http', '$location', '$filter', function ($scope, $rootScope, $modalInstance, param, $http, $location, $filter) {

    $scope.info = {};
    $scope.info.showTypes = []
    $scope.info.types = ["DEV", "QA", "UAT"];
    angular.forEach($scope.info.types, function (type) {
        var isExist = 0;
        angular.forEach(param.types, function (ptype) {
            if (type == ptype) {
                isExist = 1;
                return false;
            }
        });
        if (isExist == 0) {
            var obj = {};
            obj.type = type;
            obj.check = false;
            $scope.info.showTypes.push(obj);
        }
    });
    $scope.info.plan_name = param.plan_name;
    $scope.info.plan_id = param.plan_id;
    $scope.info.desc = "";
    $scope.info.selectPlan = '';
    $scope.info.startExceptTime = new Date(param.projectPlanInfo.projectPlanStartupTime);
    $scope.info.endExceptTime = new Date(param.projectPlanInfo.projectPlanOnlineTime);
    // $scope.startTime = false;
    // $scope.endTime = false;
    $scope.userName = getUserName();

    $scope.info.planList = [];

    $http.get(beetle_plan_url + '/project_plan/getPlanList?token_id=' + getTokenId() + '&isShowOnline=false').success(function (data) {
        $scope.info.planList = data.data;
    });

    $scope.save = function () {
        var plan_id = '';
        var plan_name = '';
        if (new Date($scope.info.endExceptTime) < new Date($scope.info.startExceptTime)) {
            $rootScope.showMessage("error", "失败", "结束时间小于等于开始时间");
            return false;

        }

        var index = 0;
        angular.forEach($scope.info.showTypes, function (obj) {
            if (obj.check) {
                index = 1;
            }
        });

        if (index == 0) {
            $rootScope.showMessage("error", "失败", "请选择环境类型");
            return false;
        }
        if ($scope.info.desc == '') {
            $rootScope.showMessage("error", "失败", "区域要求/描述不能为空");
            return false;
        }

        plan_id = $scope.info.plan_id;
        plan_name = $scope.info.plan_name;
        angular.forEach($scope.info.showTypes, function (obj) {
            if (obj.check) {
                $http.get(ucloud_master_url + '/api/v1/apply_record/add?type=' + obj.type + '&applicant_id=' + getUserId() + '&expect_recover_date=' + $filter('date')($scope.info.endExceptTime, "yyyy-MM-dd HH:mm:ss") + '&token_id=' + getTokenId() + '&plan_name=' + plan_name + '&plan_id=' + plan_id + '&start_date=' + $filter('date')($scope.info.startExceptTime, "yyyy-MM-dd HH:mm:ss") + '&applicant_name=' + getUserName() + '&desc=' + $scope.info.desc).success(function (data) {
                    if (data.success == true) {
                        $scope.cancel();
                    } else {
                        alert(data.msg);
                    }
                })
            }
        });
    };

    $scope.cancel = function () {
        // 关闭弹出框
        $modalInstance.dismiss('cancel');
    };

}]);
